package com.envir.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.envir.pojo.User;
import com.envir.utils.R;
import com.envir.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    //依赖注入
    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public R login(@RequestBody User user, HttpSession session){
        //密码加密
        String password = user.getPassword();
//        password = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));
        //根据密码查询用户
        LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
        qw.eq(User::getUsername,user.getUsername());
        User one = userService.getOne(qw);
        //比较用户
        if(one == null){
            log.info("用户名不存在");
            return R.error("用户名不存在");
        }
        //比较密码
        if(!password.equals(one.getPassword())){
            log.info("密码错误");
            return R.error("密码错误");
        }
        //是否禁用
        if(one.getStatus() == 0){
            log.info("用户被禁用");
            return R.error("用户被禁用");
        }
        //存入会话
        session.setAttribute("auth",one.getId());
        //返回
        return R.success(one);
    }

    @PostMapping("/register")
    public R register(@RequestBody User user){
        log.info("user:{}",user);
        LocalDateTime currentDateTime = LocalDateTime.now();
        //判断用户名是否存在
        User byId = userService.getById(user.getId());
        if (byId==null) {
            user.setPassword(user.getPassword());
            user.setStatus(1);
            user.setCreateTime(currentDateTime);
            user.setUpdateTime(currentDateTime);
            userService.save(user);
            System.err.println(user);
            return R.success("新增成功");
        }else {
            System.err.println(
                    2111
            );
            return R.error("新增失败");
        }
    }
}
